package com.kfm.servlet;

import com.kfm.model.Account;
import com.kfm.service.AccountService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet("/account")
public class AccountServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        AccountService service = new AccountService();

        List<Account> all = service.findAll();

        resp.setContentType("text/html;charset=utf-8");

        StringBuffer sb = new StringBuffer();
//        sb.append("<link rel=\"stylesheet\" href=\"static/css/index.css\">");

        sb.append("""
                <h1 style="text-align:center;">用户列表</h1>
                <table width="800px" border="1" cellspacing="0">
                    <tr>
                        <th>编号</th>
                        <th>用户名</th>
                        <th>操作</th>
                    </tr>
                """);
        if (all == null || all.size() == 0){
            sb.append("""
                    <tr style="text-align:center;">
                        <td colspan="4"> 没有数据 </td>
                    </tr>
                    """);
        } else{
            for (int i = 0; i < all.size(); i ++){
                int num = i +1;
                Account account = all.get(i);


                sb.append("""
                    <tr>
                        <td>%s</td>
                        <td>%s</td>
                        <td><a href="deleteAccount?id=%s" target="_blank">删除</a></td>
                    </tr>
                    """.formatted(num, account.getUsername(), account.getId()));
            }
        }

        sb.append("</table>");

        PrintWriter writer = resp.getWriter();


        writer.write(sb.toString());
    }
}
